package com.hengmei.smallscreen.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatButton
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.hengmei.smallscreen.R
import com.hengmei.smallscreen.adapter.BleAdapter
import com.hengmei.smallscreen.adapter.WifiAdapter
import com.hengmei.smallscreen.base.BaseActivity
import com.hengmei.smallscreen.databinding.ActivitySettingBinding
import com.hengmei.smallscreen.entity.GlobalNotificationEntity
import com.hengmei.smallscreen.event.GlobalNotification
import com.hengmei.smallscreen.manager.ClientManager
import com.hengmei.smallscreen.mmkv.DataRepository
import com.hengmei.smallscreen.utils.AntiShake
import com.hengmei.smallscreen.utils.getCode
import com.hengmei.smallscreen.utils.toast
import com.hengmei.smallscreen.widget.RegexEditText
import com.hengmei.smallscreen.widget.UIImageView
import com.hengmei.smallscreen.wifimanager.IWifi
import com.hengmei.smallscreen.wifimanager.IWifiManager
import com.hengmei.smallscreen.wifimanager.OnWifiChangeListener
import com.hengmei.smallscreen.wifimanager.OnWifiConnectListener
import com.hengmei.smallscreen.wifimanager.OnWifiStateChangeListener
import com.hengmei.smallscreen.wifimanager.State
import com.hengmei.smallscreen.wifimanager.WifiManager
import com.hjq.language.MultiLanguages
import com.inuker.bluetooth.library.BluetoothClient
import com.inuker.bluetooth.library.search.SearchRequest
import com.inuker.bluetooth.library.search.SearchResult
import com.inuker.bluetooth.library.search.response.SearchResponse
import com.inuker.bluetooth.library.utils.StringUtils
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBindView
import java.util.Locale


//TAG
private const val TAG = "KEVIN_Bluetooth"

class SettingActivity : BaseActivity<ActivitySettingBinding>(ActivitySettingBinding::inflate),
    OnWifiChangeListener, OnWifiStateChangeListener, OnWifiConnectListener {

    private var wifiAdapter: WifiAdapter?=null
    private var mClient: BluetoothClient?=null
    private var mDevices: ArrayList<SearchResult>? = null

    private var mBleAdapter: BleAdapter? = null
    var addressData : MutableLiveData<String> ?=null

//    wifi 相关

    var manager: IWifiManager? = null
    var wifis: List<IWifi>? = null
    private  var changeTag = "0"
    private val requestLocationPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
            if (isPermissionGranted) {

            } else {
                toast("BluetoothReading...")
            }
        }
    companion object {
        val KEY_TRANSFER: String? = "tag"

        fun start(mainActivity: Activity) {
            mainActivity.startActivity(Intent(mainActivity,SettingActivity::class.java))
        }
    }
    override fun initView() {

        mDevices = ArrayList()
        mClient = ClientManager().getClient()
        addressData = MutableLiveData()
        addressData?.value = DataRepository.bleAddress
        addressData?.observe(this) {
            binding.tvBluetoothConnection.text = it
            DataRepository.bleAddress = it
        }
        initWifi()
    }

    private fun initWifi() {

        wifis = java.util.ArrayList()
        manager = WifiManager.create(me)
        manager!!.setOnWifiChangeListener(this)
        manager!!.setOnWifiConnectListener(this)
        manager!!.setOnWifiStateChangeListener(this)
    }


    override fun initViewEvents() {

        setOnClickListener(binding.tvBluetoothConnection,binding.buttonBack,binding.buttonSave,binding.tvWifi,binding.tvLanguage)

        initData()

    }

    private fun initData() {
        binding.etInspector.setText(DataRepository.inspector)
        binding.etTestingUnit.setText(DataRepository.testingUnit)
        binding.etUnitInspected.setText(DataRepository.unitInspected)
        binding.etTel.setText(DataRepository.tel)
        binding.etUpAddress.setText(DataRepository.upAddress)
        binding.etUpUser.setText(DataRepository.upUser)
        binding.etUpPwd.setText(DataRepository.upPwd)
        binding.etTitle.setText(DataRepository.homeTitle)
        var code = getCode()
        binding.tvVersions.text = "Version 23.12 code:$code"
        val locale = MultiLanguages.getAppLanguage(this)

        if (locale == Locale.ENGLISH) {
            binding.tvLanguage.text = resources.getString(R.string.language_us)
        } else {
            binding.tvLanguage.text = resources.getString(R.string.language_china)
        }
    }

    override fun onClick(v: android.view.View?) {
        super.onClick(v)
        when(v){
            binding.tvBluetoothConnection -> {
                showBleDialog()
                WaitDialog.show("Please Wait!")
                Handler(Looper.getMainLooper()).postDelayed(Runnable { WaitDialog.dismiss() }, 5000)
            }
            binding.buttonBack -> {

                finish()
            }
            binding.buttonSave -> {
                saveData()
                toast(getString(R.string.saveSuccess))
            }
            binding.tvWifi -> {
                showSelectDialog()
            }
            binding.tvLanguage -> {
//                LanguageActivity.start(me)

                changeTag = "1"
                val locale = MultiLanguages.getAppLanguage(this)

                if (locale == Locale.ENGLISH) {
                    MultiLanguages.setAppLanguage(me, Locale.CHINA)
                    binding.tvLanguage.text = resources.getString(R.string.language_us)
                    toast("切换中文,重启后生效!")

                } else {
                    MultiLanguages.setAppLanguage(me, Locale.ENGLISH)
                    binding.tvLanguage.text = resources.getString(R.string.language_china)
                    toast("SWITCH_ENGLISH,TakeEffectAfterRestart!")
                }

//                setResult(RESULT_OK, intent.putExtra(KEY_TRANSFER, changeTag))

                recreate()

            }
        }

    }

    private fun saveData() {
//    et_testingUnit et_UnitInspected et_Tel et_upAddress et_upUser et_upPwd
        var insperctor = binding.etInspector.text.toString()
        var unit = binding.etTestingUnit.text.toString()
        var unitInspected = binding.etUnitInspected.text.toString()
        var tel = binding.etTel.text.toString()
        var address = binding.etUpAddress.text.toString()
        var user = binding.etUpUser.text.toString()
        var pwd = binding.etUpPwd.text.toString()
        var title = binding.etTitle.text.toString()

        if(insperctor.isNotEmpty()){
            DataRepository.inspector = insperctor
        }
        if(unit.isNotEmpty()){
            DataRepository.testingUnit = unit
        }
        if(unitInspected.isNotEmpty()){
            DataRepository.unitInspected = unitInspected
        }
        if(tel.isNotEmpty()){
            DataRepository.tel = tel
        }
        if(address.isNotEmpty()){
            DataRepository.upAddress = address
        }
        if(user.isNotEmpty()){
            DataRepository.upUser = user
        }
        if(pwd.isNotEmpty()){
            DataRepository.upPwd = pwd
        }
        if(title.isNotEmpty()){
            DataRepository.homeTitle = title
            GlobalNotification.get().postModbus(GlobalNotificationEntity(1,title))

//            LiveDataEvent.get().postModbus(title)
        }

    }

    private fun searchBle(){

//        判断安卓版本是否大于6.0
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){

            requestLocationPermission.launch(Manifest.permission.BLUETOOTH_CONNECT)
            requestLocationPermission.launch(Manifest.permission.BLUETOOTH_SCAN)

        }
        val request = SearchRequest.Builder()
            .searchBluetoothLeDevice(3000, 1)   // 先扫BLE设备3次，每次3s
            .build()
//        扫描蓝牙
        mClient?.search(request, object : SearchResponse {
            override fun onSearchStarted() {}
            override fun onDeviceFounded(device: SearchResult) {
//                val beacon = Beacon(device.scanRecord)
                if (!mDevices!!.contains(device)) {
                    var name = device.name
                    if(StringUtils.isNotBlank(name)){
                        if(name.equals("NULL")){

                        }else{
                            mDevices?.add(device)
                        }
                    }
                    if(mBleAdapter!=null){
                        mBleAdapter!!.notifyDataSetChanged()
                    }
//                  mAdapter.setDataList(mDevices);
                }
                Log.d(TAG, "onDeviceFounded: "+device.name)
            }

            override fun onSearchStopped() {}
            override fun onSearchCanceled() {}
        })

    }


    /*
    * 扫描 蓝牙 弹窗
    * */
    private fun showBleDialog() {

        CustomDialog.show(object :
            OnBindView<CustomDialog>(R.layout.dialog_ble) {
            override fun onBind(dialog: CustomDialog, v: View) {
                val btn_close: UIImageView = v.findViewById(R.id.btn_close)
                val btn_ok: AppCompatButton = v.findViewById(R.id.scanf)
                val rvBle = v.findViewById<RecyclerView>(R.id.rv_ble)
                rvBle.layoutManager = LinearLayoutManager(
                    this@SettingActivity,
                    LinearLayoutManager.VERTICAL,
                    false
                )
                mBleAdapter = BleAdapter(R.layout.item_ble, mDevices)
                rvBle.adapter = mBleAdapter

                mBleAdapter?.addChildClickViewIds(R.id.ble_item)
                mBleAdapter?.setOnItemChildClickListener { adapter, view, position ->
                    if(AntiShake.check(view)){
                        return@setOnItemChildClickListener
                    }
                    when(view.id){
                            R.id.ble_item -> {
                                val device = mDevices?.get(position)
                                val address = device?.address
                                addressData?.value = address
                                dialog.dismiss()
                        }
                    }

                }

                btn_ok.setOnClickListener(View.OnClickListener { v ->
                    if (AntiShake.check(v)) {
                        return@OnClickListener
                    }
                    searchBle()
//                    dialog.dismiss()

                })
                btn_close.setOnClickListener(View.OnClickListener { v ->
                    if (AntiShake.check(v)) {
                        return@OnClickListener
                    }
                    dialog.dismiss()
                })
                searchBle()
            }
        }).maskColor = Color.parseColor("#4D000000")


    }

    /*
     * wifi 选择弹窗 列表
     *
     * */
    private fun showSelectDialog() {
        CustomDialog.show(object : OnBindView<CustomDialog>(R.layout.dialog_select_wifi) {
            override fun onBind(dialog: CustomDialog, v: View) {
                val rv: RecyclerView
                val wifi_refresh: AppCompatButton
                val closeDialog: UIImageView
                closeDialog = v.findViewById(R.id.btn_close)
                wifi_refresh = v.findViewById(R.id.wifi_refresh)
                rv = v.findViewById(R.id.select_more_rv)
                rv.layoutManager = LinearLayoutManager(me)
                closeDialog.setOnClickListener(View.OnClickListener { v ->
                    if (AntiShake.check(v)) {
                        return@OnClickListener
                    }
                    dialog.dismiss()
                })
                wifiAdapter = WifiAdapter(R.layout.item_wifi, wifis)
                rv.adapter = wifiAdapter
                wifiAdapter?.addChildClickViewIds(R.id.select_test)
                wifiAdapter?.setOnItemChildClickListener(OnItemChildClickListener { adapter, view, position -> /*
                                           * 点击连接
                                           * */

                    if (wifis?.get(position)!!.isConnected()) {
                        /*
                                               * 断开操作
                                               * */
                        manager?.removeWifi(wifis?.get(position))

                        manager?.disConnectWifi()
                    } else {

                        CustomDialog.show(object :
                            OnBindView<CustomDialog>(R.layout.dialog_input_wifi) {
                            override fun onBind(inputDialog: CustomDialog, inputView: View) {
                                val input2: RegexEditText
                                val close: UIImageView
                                val wifi_connect: AppCompatButton
                                wifi_connect = inputView.findViewById(R.id.wifi_connect)
                                input2 = inputView.findViewById(R.id.input_2)
                                close = inputView.findViewById(R.id.btn_close)
                                wifi_connect.setOnClickListener(View.OnClickListener { v ->
                                    if (AntiShake.check(v)) {
                                        return@OnClickListener
                                    }
                                    val wifiPw: String = input2.getText().toString()
                                    if (TextUtils.isEmpty(wifiPw)) {
                                        toast(getString(R.string.nullCheck))
                                        return@OnClickListener
                                    }
                                    manager?.removeWifi(wifis?.get(position))
                                    manager?.connectEncryptWifi(
                                        wifis?.get(position),
                                        input2.getText().toString()
                                    )
                                    inputDialog.dismiss()
                                })
                                close.setOnClickListener { inputDialog.dismiss() }
                            }
                        }).maskColor = Color.parseColor("#4D000000")
                    }
                })
                wifiAdapter?.setEmptyView(R.layout.layout_empty)
                wifi_refresh.setOnClickListener(View.OnClickListener { manager?.scanWifi() })

                //                scanWifi()
            }
        }).maskColor = Color.parseColor("#4D000000")

    }

    override fun onWifiChanged(wifis: MutableList<IWifi>?) {

        Log.d("kevinwifi1", wifis.toString())
        binding.tvWifi.text = ""
        this.wifis = wifis
        for (wifi in wifis!!) {

            if(wifi.isConnected()){
                binding.tvWifi.text = wifi.name()
            }
        }
        if (wifiAdapter != null) {
            wifiAdapter!!.setList(wifis)
            wifiAdapter!!.notifyDataSetChanged()
        }

    }


    override fun onConnectChanged(status: Boolean) {
    }

    override fun onStateChanged(state: State?) {
    }

    override fun onDestroy() {
        manager?.destroy()

        super.onDestroy()
    }


}